﻿
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using LowCoding.Common.JWT;
using System.Text;

namespace LowCoding.Common.Security
{
    public class AppManager
    {
        public static LoginUserDto GetCurrentUser()
        {
            return GetCurrentUser<LoginUserDto>();
        }

        public static AppletUserDto GetAppletUser()
        {
            return GetCurrentUser<AppletUserDto>();
        }

        /// <summary>
        /// 从Token中获取出来用户信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetCurrentUser<T>() where T : class
        {
            var token = HttpContext.Current.Request.Headers["Authorization"].FirstOrDefault();
            if (token == null)
            {
                return default(T);
            }
            if (token.Contains("Bearer"))
            {
                token = token.Replace("Bearer ", "");
            }
            return JwtTokenHelper.GetUserDto<T>(token);
        }

        #region MyRegion
        ///// <summary>
        ///// 汤文
        ///// 2021/08/23
        ///// 根据token查询登录用户信息
        ///// </summary>
        ///// <param name="token"></param>
        ///// <returns></returns>
        //public static T GetUserDto<T>(string token) where T : class
        //{
        //    if (string.IsNullOrWhiteSpace(token))
        //        return default(T);

        //    byte[] key = Encoding.UTF8.GetBytes(AppSettings.JwtSecretKey);
        //    IJsonSerializer serializer = new JsonNetSerializer(); //序列化
        //    IDateTimeProvider provider = new UtcDateTimeProvider();
        //    IJwtValidator validator = new JwtValidator(serializer, provider);
        //    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); //base64加解密
        //    IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); //加密方式
        //    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
        //    try
        //    {
        //        //解密
        //        return decoder.DecodeToObject<T>(token, key, verify: true);
        //    }
        //    catch
        //    {
        //        //throw new BusinessException("登录过期！");
        //        return default(T);
        //    }
        //}
        #endregion

        
        /// <summary>
        /// 汤文
        /// 2021/08/23
        /// 根据用户实体与过期时间 得到 Jwt
        /// </summary>
        /// <param name="userDto"></param>
        /// <param name="ExpiryDateTime"></param>
        /// <returns></returns>
        public static string GetJwtString<T>(T playloadDto, DateTime ExpiryDateTime)
        {
            playloadDto.SetPropertyValue("ExpiryDateTime", ExpiryDateTime);
            // 验证
            byte[] key = Encoding.UTF8.GetBytes(AppSettings.JwtSecretKey);
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); //加密方式
            var serializer = new JsonNetSerializer(); //序列化
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); //base64加解密
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(playloadDto, key); //生成令牌

        }
    }

    public class LoginUserDto
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserId { get; set; }

        /// <summary>
        /// 用户代码
        /// </summary>
        public string UserCode { get; set; }

        /// <summary>
        /// 用户名称
        /// </summary>
        public string UsrName { get; set; }

        /// <summary>
        /// 企业id
        /// </summary>
        public string UsrFltId { get; set; }

        /// <summary>
        /// 企业代码
        /// </summary>
        public string UsrFltCode { get; set; }

        /// <summary>
        /// 企业名称
        /// </summary>
        public string UsrFltName { get; set; }

        /// <summary>
        /// 统一社会信用代码
        /// </summary>
        public string UsrCreditcode { get; set; }

        /// <summary>
        /// 手机号码
        /// </summary>
        public string UsrPhone { get; set; }

        /// <summary>
        /// 是否是角色管理员
        /// </summary>
        public bool IsRoleAdmin { get; set; }

        /// <summary>
        /// 用户头像
        /// </summary>
        public string UserAvatar { get; set; }

        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime ExpiryDateTime { get; set; }

        /// <summary>
        /// 登录平台 1 后台 2 小程序
        /// </summary>
        public string PlatForm { get; set; }

        /// <summary>
        /// 部门名称
        /// </summary>
        public string UsrDptName { get; set; }
    }

    public class AppletUserDto
    {
        /// <summary>
        /// ID
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 电话号码
        /// </summary>
        public string Phone { get; set; }

        /// <summary>
        /// 部门名称
        /// </summary>
        public string Departname { get; set; }

        /// <summary>
        /// 公司名称
        /// </summary>
        public string Companyname { get; set; }

        /// <summary>
        /// 用户类型
        /// </summary>
        public string Usertype { get; set; }

        /// <summary>
        /// 用户邮箱
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// 组织机构代码
        /// </summary>
        public string Orgcode { get; set; }

        /// <summary>
        /// 角色集合
        /// </summary>
        public string Roles { get; set; }

        /// <summary>
        /// 用户名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 报关员卡号
        /// </summary>
        public string Orgcustoms { get; set; }

        /// <summary>
        /// 统一社会信用代码
        /// </summary>
        public string Creditcode { get; set; }

        /// <summary>
        /// 登录名
        /// </summary>
        public string Loginname { get; set; }

        /// <summary>
        /// 手机号码
        /// </summary>
        public string Mobile { get; set; }

        /// <summary>
        /// 海关10位备案编码
        /// </summary>
        public string Orgcustomscode { get; set; }

        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime ExpiryDateTime { get; set; }
    }
}